#include "lastfm.h"

/*

 This file is rewrited copy of apiclient.cpp from LastGo project
 Thanks for it's creator, it's great help for this project ;-)


 */
last::last(QString d1,QString d2){


this->user=d1;
this->password=d2;

if (this->user.isEmpty()||this->password.isEmpty())return;
    apikey="2313b128f125d021405d5ff75afcbfa3";
    secret="312eaa2d57b0feaca65d7fbcf462e648";


            Utils *u = new Utils();

              QString token = u->getAuthToken(d1, d2);

              QMap<QString, QString> params;
              params["username"] = this->user;
              params["authToken"] = token;
              params["api_key"] = apikey;
              params["method"] = "auth.getMobileSession";

              QString signature = u->buildSignature(params, secret);
              params["api_sig"] = signature;

              QString api_url = u->buildApiUrl(LASTFM_BASE_URL, params);

              Requests *r = new Requests(this);
              connect(r, SIGNAL(dataAvailable(QString)), this, SLOT(authGetMobileSessionReply(QString)));
              r->apiRequest(api_url);


}

last::~last(){

}


void last::authGetMobileSessionReply(QString data)
{
    QXmlStreamReader xml;
    xml.addData(data);

    QMap<QString, QString> response;
    QString status;

    while (!xml.atEnd())
    {
        xml.readNext();

        if (xml.isStartElement())
        {
            if(xml.name() == "lfm")
            {
                status = xml.attributes().value("status").toString();
                response["status"] = status;
            }
            else
            {
                if(status == "ok")
                {
                    if(xml.name() == "name")
                        response[xml.name().toString()] = xml.readElementText();
                    if(xml.name() == "key"){
                        response[xml.name().toString()] = xml.readElementText();
                    this->sk = response[xml.name().toString()];
                }
                    if(xml.name() == "subscriber")
                        response[xml.name().toString()] = xml.readElementText();
                }
                else if(status == "failed")
                {
                    if(xml.name() == "error")
                    {
                        response["error"] = xml.attributes().value("code").toString();
                        response["message"] = xml.readElementText();
                    }
                }
            }
        }
    }

// if response["status"]="ok" then =)
scrobblerHandshake();
    emit authGetMobileSessionData(response);

}

void last::scrobblerHandshake()
{
    if (this->user.isEmpty()||this->password.isEmpty())return;

    Utils *u = new Utils();
    QDateTime now = QDateTime::currentDateTime();
 QString timestamp = QString::number(now.toTime_t());
 QString token = u->getScrobblerAuthToken(secret, timestamp);
 // api_key, sk
    QMap<QString, QString> params;
    params["hs"] = "true";
    params["p"] = "1.2.1";
    params["c"] = "tst";
    params["v"] = "1.0";
    params["u"] = this->user;
    params["t"] =timestamp;
    params["a"] = token;
    params["api_key"] = this->apikey;
    params["sk"] =this->sk;

    QByteArray post_params = u->buildPostParameters(params);

    Requests *r = new Requests(this);
    connect(r, SIGNAL(dataAvailable(QString)), this, SLOT(scrobblerHandshakeReply(QString)));
    r->apiRequestPost(LASTFM_HANDSHAKE_URL, post_params);
}

void last::scrobblerHandshakeReply(QString data)
{

    QMap<QString, QString> reply;
    QTextStream stream(&data);

    QString reply_status = "";
    reply_status = stream.readLine();

    if(reply_status == "OK")
    {
        reply["status"] = reply_status;
        this->session_id = stream.readLine();
        this->playing_url = stream.readLine();
        this->submission_url = stream.readLine();

    }
    else
        reply["status"] = reply_status;


}


void last::now(QStringList e,int duration){
if (this->user.isEmpty()||this->password.isEmpty())return;
    if (this->playing_url==""){
        scrobblerHandshake();
        return;
    }

   Utils *u = new Utils();

      int lenght = duration  / 1000;

      QMap<QString, QString> params;
      params["s"] = this->session_id;
      params["a"] = e.at(2);
      params["t"] = e.at(1);
      params["b"] = e.at(4);
      params["l"] = QString::number(lenght);;
      params["n"] = "";
      params["m"] = "";

      QByteArray post_params = u->buildPostParameters(params);


      Requests *r = new Requests(this);
     connect(r, SIGNAL(dataAvailable(QString)), this, SLOT(scrobblerPlayingReply(QString)));
      r->apiRequestPost( this->playing_url, post_params);

}

void last::addTrack(QStringList e,int duration){
if (this->user.isEmpty()||this->password.isEmpty())return;
    if (this->playing_url==""){
        scrobblerHandshake();
        return;
    }
    QDateTime now = QDateTime::currentDateTime();
 QString timestamp = QString::number(now.toTime_t());

   Utils *u = new Utils();

      int lenght = duration  / 1000;


      QMap<QString, QString> params2;
          params2["s"] = this->session_id;
          params2["a[0]"] = e.at(2);
          params2["t[0]"] = e.at(1);
          params2["i[0]"] = timestamp;
          params2["o[0]"] = "P";
          params2["r[0]"] = "";
          params2["l[0]"] = QString::number(lenght);
          params2["b[0]"] = e.at(4);
          params2["n[0]"] = "";
          params2["m[0]"] = "";

 QByteArray post_params2 = u->buildPostParameters(params2);
          Requests *r2 = new Requests(this);
          connect(r2, SIGNAL(dataAvailable(QString)), this, SLOT(scrobblerPlayingReply(QString)));
          r2->apiRequestPost( this->submission_url, post_params2);

}

void last::scrobblerPlayingReply(QString data){

}
